<template>
  <el-card class="box-card card-header m-t-20">
    <div slot="header" class="clearfix f-medium">
      <i class="fa fa-bar-chart m-r-10 text-c-blue" aria-hidden="true"></i>
      <span>水质数据表</span>
    </div>
    <div class="">
      <div class="m-b-20 p-l-10 f-medium flex-row-between">
        <div>
          <span class="text-c-blue f-w-600 m-r-10">当前：{{ showState }}</span>
          <span><el-button type="info" plain size="mini" round :disabled="restoreBtn"
              @click="rePlaySocket">恢复同步</el-button></span>
        </div>
        <div>
          <span class="text-c-blue f-w-600 m-r-10">数据间隔:</span>
          <el-select v-model="rate" placeholder="选择数据间隔" @change="changeRate">
            <el-option v-for="item in rateOptions" :key="item.value" :label="item.label" :value="item.value" size="mini">
            </el-option>
          </el-select>
        </div>
      </div>
      <div id="chart-WaterQuality">
        <EchartsCreator ref="waterQualityChart" :options="chartsOption" dark></EchartsCreator>
      </div>

    </div>
    <el-dialog :title="target" :visible.sync="dialogVisible" width="450px" @close="toGetParamRange">
      <p class="m-b-15">请在符合相应的指标范围下修改传感器指标。</p>
      <div class="flex-row-center m-b-10" v-for="item in sensorList">
        <el-col :span="5">
          <h1 style="width:100px ;">{{ item.name }}</h1>
        </el-col>
        <el-col :span="7">
          <el-input v-model="item.foot" placeholder="下限" size="small"></el-input>
        </el-col>
        <el-col class="text-center" :span="1">~</el-col>
        <el-col :span="7">
          <el-input v-model="item.top" placeholder="上限" size="small"></el-input>
        </el-col>
        <el-col :span="4">
          <span class="p-l-10">{{ item.unit }}</span>
        </el-col>
      </div>
      <span slot="footer" class="flex-row-around">
        <el-button type="primary" @click="changeRange">保存修改</el-button>
        <el-button @click="dialogVisible = false;">关闭窗口</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { getWaterData, getParamRange, updateParamRange } from "@/api/waterAnalysis";
import WebSocket from "@/utils/websocketPackage";
// 节流定义
var throttleRate = 1000;
var throttleTimer = null;
import { chartsOption, range } from '../config/water-charts-options'
export default {
  name: "WaterCharts",
  data() {
    return {
      target: '水域4516IAUW812',
      state1: '',
      state2: '',
      sensorList: [
        { id: 1, name: '水温', unit: '°C', foot: 5, top: 30 },
        { id: 2, name: 'PH值', unit: '', foot: 6.58, top: 8.5 },
        { id: 3, name: '水浊度', unit: 'FTU', foot: 0, top: 2000 },
        { id: 4, name: 'TDS', unit: 'Lux', foot: 0, top: 500 },
        { id: 5, name: '光照强度', unit: 'mg/L', foot: 0, top: 1000 },
      ],
      dialogVisible: false,
      // 恢复同步按钮
      restoreBtn: false,
      showState: "实时同步",
      // 数据传输频率调整
      rateOptions: [
        {
          value: 1000,
          label: "1秒",
        },
        {
          value: 3000,
          label: "3秒",
        },
        {
          value: 5000,
          label: "5秒",
        },
        {
          value: 10000,
          label: "10秒",
        },
      ],
      // 当前的数据频率
      rate: 1000,
      // 异常数值的范围
      // range: {
      //   ph: [6.58, 8.5], //正常的湖泊与河流,ph值约6.5到8.5
      //   temperature: [5, 30], //水热污染的超标范围：33度
      //   turbidity: 2000, //浊度一般不超过3000
      //   illumination: 3000,//光照强度不超过3000
      //   TDS: 500,//饮用自来水tds一般不超过500
      // },
      socket: null,
      options: {
        url: "ws://175.178.124.20:8589/state/张三",
        onmessage: (res) => {
          if (!throttleTimer) {
            throttleTimer = setTimeout(() => {//这里用箭头函数就不会干扰this的指向。
              let result = JSON.parse(res);
              console.log(result);
              this.updataSingleData(result)
              throttleTimer = null;
            }, throttleRate);
          }
        },
        // 保活周期 10s
        timer: 30000,
        // 断线重连
        reconnect: true,
      },
      // oriColors: ["red", "#0066ff", "#7cffb2", "#fddd60", "#6fb6f5"],
      // empColors: ["#EE6666", "#58d9f9", "#05c091", "#ff8a45"],
      chartsOption,
      range,
      dataSet: {
        illumination: [],
        ph: [],
        temperature: [],
        turbidity: [],
        TDS: [],
        date: [],
      },
    };
  },
  mounted() {
    //绑定函数，用于关闭socket连接，处理修改图表显示
    this.$bus.$on("closeSocket", this.closeSocket);
    // 获取最新的水质数据
    getWaterData()
      .then((data) => {
        // 获取传感器指标
        this.toGetParamRange();
        this.updataChartData(data);
        this.openSocket(); //开启连接
      })
      .catch((err) => {
        console.log(err);
      });
    this.chartsOption.toolbox.feature.myThreshold.onclick = () => {
      this.dialogVisible = true;
    }
  },
  // 组件销毁时关闭socket
  beforeDestroy() {
    this.socket.close();
    this.socket = null;
  },
  methods: {
    // 更新图表数据-整体替换
    updataChartData(data) {
      let dataSet = this.dataSet;
      for (let item in data) {
        dataSet.date.unshift(data[item].time);
        dataSet.temperature.unshift(data[item].wTemp);
        dataSet.ph.unshift(data[item].ph);
        dataSet.turbidity.unshift(data[item].zuodu);
        dataSet.TDS.unshift(data[item].tds);
        dataSet.illumination.unshift(data[item].light);
      }
      this.$refs.waterQualityChart.setOption({
        xAxis: [
          {
            data: dataSet.date,
          },
        ],
        series: [
          { data: dataSet.temperature },
          { data: dataSet.ph },
          { data: dataSet.turbidity },
          { data: dataSet.illumination },
          { data: dataSet.TDS },
        ],
      });
    },
    // 同步加入单条数据
    updataSingleData(result) {
      let dataSet = this.dataSet;
      // 对最旧的数据进行删除
      for (let item in dataSet) {
        this.dataSet[item].shift();
      }
      // 插入最新的一条数据
      dataSet.temperature.push(result.wTemp);
      dataSet.ph.push(result.ph);
      dataSet.turbidity.push(result.zuodu);
      dataSet.illumination.push(result.light);
      dataSet.TDS.push(result.tDS);
      dataSet.date.push(result.time);
      this.$refs.waterQualityChart.setOption({
        xAxis: [
          //x轴设置
          {
            data: dataSet.date,
          },
        ],
        series: [
          { data: dataSet.temperature },
          { data: dataSet.ph },
          { data: dataSet.turbidity },
          { data: dataSet.illumination },
          { data: dataSet.TDS },
        ],
      });
      this.dataSet = dataSet;
    },
    // 恢复同步
    rePlaySocket() {
      // 获取最新的水质数据
      getWaterData()
        .then((data) => {
          this.dataSet = {
            illumination: [],
            ph: [],
            temperature: [],
            turbidity: [],
            TDS: [],
            date: [],
          };
          this.updataChartData(data); // 更新图表
          this.openSocket(); //开启连接
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 开启websocket
    openSocket() {
      this.showState = "实时同步";
      this.restoreBtn = true;
      this.socket = new WebSocket(this.options);
    },
    // 主动关闭websocket连接，显示某一天的数据
    closeSocket(res) {
      let { time, data } = res;
      let tip = "";
      if (data.length == 0) {
        tip = "当天无数据！";
      } else {
        tip = "已更新图表显示";
        // 关闭websocket连接：
        if (this.socket) {
          this.socket.close();
          this.socket = null;
        }
        // 修改显示'某一天'，更新图表
        this.showState = time;
        // 恢复同步按钮
        this.restoreBtn = false;
        this.updataChartData(data);
      }
      this.$Notify(tip);
    },
    // 获取传感器指标
    async toGetParamRange() {
      let res = await getParamRange();
      let { sensorList, range } = this;
      // 对输入框的赋值
      sensorList[0].foot = Number(res.tempLowerLimit);
      sensorList[0].top = Number(res.tempTopLimit);

      sensorList[1].foot = Number(res.phLowerLimit);
      sensorList[1].top = Number(res.phTopLimit);

      sensorList[2].foot = Number(0);
      sensorList[2].top = Number(res.zuoduLowerLimit);

      sensorList[3].foot = Number(res.tdslowerLimit);
      sensorList[3].top = Number(res.tdstopLimit);

      sensorList[4].foot = Number(0);
      sensorList[4].top = Number(res.lightLowerLimit);
      // 对图表的判断修改：
      range.temperature = [this.sensorList[0].foot, this.sensorList[0].top];
      range.ph = [this.sensorList[1].foot, this.sensorList[1].top];
      range.turbidity = this.sensorList[2].top;
      range.TDS = this.sensorList[3].top;
      range.illumination = this.sensorList[4].top;
      return true

    },
    // 修改传感器阈值
    changeRange() {
      let oRang = this.sensorList;
      let newRang = {
        phLowerLimit: oRang[1].foot,
        phTopLimit: oRang[1].top,
        tempLowerLimit: oRang[0].foot,
        tempTopLimit: oRang[0].top,
        zuoduLowerLimit: oRang[2].top,
        zuoduTopLimit: oRang[2].foot,
        lightLowerLimit: oRang[4].top,
        lightTopLimit: oRang[4].foot,
        tdstopLimit: oRang[3].top,
        tdslowerLimit: oRang[3].foot
      }
      updateParamRange(JSON.stringify(newRang)).then(() => {
        this.dialogVisible = false;
        this.$Notify('已修改传感器警告阈值');
      }).catch((err) => {
        this.$Notify("请求异常!", 'error');
      })
    },
    // 修改阈值
    changeRate(e) {
      throttleRate = e;
    }
  },
};
</script>

<style  scoped lang="less">
#chart-WaterQuality {
  width: 100%;
  height: 500px;
}
</style>